package com.koron.tool.dialog;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import com.koron.tool.Constant;
import com.koron.tool.MainFrame;
import com.koron.ui.MutableGridLayout;
import com.koron.ui.TableParseAction;
import com.koron.util.MyClassLoader;

@SuppressWarnings("serial")
public class BeanDialog extends JDialog {
    private DefaultTableModel model = null;
    private JTable table = null;
    private JTextField jtfClass = new JTextField();
    private ResourceBundle resourceBuddle = ResourceBundle.getBundle(MainFrame.RESOURCEBUDDLE,getLocale());

    protected BeanDialog() {
    }
    
    public BeanDialog(final MainFrame frame)
    {
        this(frame,null);
    }
    public BeanDialog(final MainFrame frame,String[][] data)
    {
        super(frame,"控制台信息",false);
        setTitle("");
        model = new DefaultTableModel(new String[]{
                resourceBuddle.getString("Decorator")
                ,resourceBuddle.getString("Type")
                ,resourceBuddle.getString("Name")
                ,resourceBuddle.getString("Memo")},0);
        table = new JTable(model);
        table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK), "parse");
        table.getActionMap().put("parse", new TableParseAction(table,TableParseAction.EXTENDROW));
        MutableGridLayout layout = new MutableGridLayout(2, 4, 5, 5);
        layout.merge(0, 1, 1, 1);
        layout.setHeight(0, 20);
        layout.setHeight(2, 20);
        layout.setHeight(3, 20);
        getContentPane().setLayout(layout);
        
        getContentPane().add(new JLabel(resourceBuddle.getString("ClassName")));
        getContentPane().add(jtfClass);
        jtfClass.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }
            
            @Override
            public void keyReleased(KeyEvent e) {
            }
            
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_ENTER)
                {
                    String classStr = jtfClass.getText();
                    if(!classStr.equals(""))
                    {
                        try {
                            Class<?> c = new MyClassLoader(new File(MainFrame.config.get(Constant.COMPILE_PATH))).loadClass(classStr);
                            model.setRowCount(0);
                            for(Field f:c.getDeclaredFields())
                            {
                                String modifier = "";
                                int modInt = f.getModifiers();
                                if(Modifier.isPublic(modInt))
                                {
                                    modifier="public";
                                }else if(Modifier.isProtected(modInt))
                                {
                                    modifier="protected";
                                }else if(Modifier.isPrivate(modInt))
                                {
                                    modifier="private";
                                }
                                model.addRow(new String[]{modifier,f.getGenericType().toString().substring(6),f.getName(),f.getName()});
                            }
                        } catch (ClassNotFoundException | MalformedURLException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
        
        table.setRowHeight(25);
        table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"","public","private","protected"})));
        table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox<>(new String[]{"java.lang.String","java.lang.Integer","java.lang.Boolean","java.lang.Double","java.util.Date"})));
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        if(data!=null)
        {
            for (String[] strings : data) {
                model.addRow(strings);
            }
        }
        JScrollPane jsp = new JScrollPane(table);
        
        jsp.setPreferredSize(new Dimension(200, 200));
        getContentPane().add(jsp);
        
        JButton btnAdd = new JButton(resourceBuddle.getString("AddLine"));
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int pos = table.getSelectedRow();
                if(pos ==-1)
                {
                    model.addRow(new String[]{"private","String","",""});
                }else
                {
                    model.insertRow(pos+1, new String[]{"private","String","",""});
                }
            }
        });
        getContentPane().add(btnAdd);
        JButton btnRemove = new JButton(resourceBuddle.getString("RemoveLine"));
        btnRemove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int pos = table.getSelectedRow();
                if(pos ==-1)
                {
                    model.setRowCount(model.getRowCount()-1);
                }else
                {
                    int rows = model.getRowCount();
                    model.removeRow(pos);
                    model.setRowCount(rows-1);
                }
            }
        });
        getContentPane().add(btnRemove);
        JButton btnSave = new JButton(resourceBuddle.getString("Save"));
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(jtfClass.getText().equals(""))
                {
                    JOptionPane.showMessageDialog(frame, resourceBuddle.getString("InputClassName"));
                    jtfClass.requestFocus();
                }else if(model.getRowCount()==0)
                {
                    JOptionPane.showMessageDialog(frame, resourceBuddle.getString("NoData"));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    String classStr = jtfClass.getText();
                    if(classStr.endsWith(".java"))
                    {
                        classStr = classStr.substring(0,classStr.indexOf(".java"));
                    }
                    String packageStr = "";
                    if(classStr.indexOf('.')!=-1)
                    {
                        if(classStr.indexOf('.')!=-1)
                        {
                            packageStr = classStr.substring(0,classStr.lastIndexOf('.'));
                            classStr = classStr.substring(classStr.lastIndexOf('.')+1);
                        }
                    }
                    sb.append("package ").append(packageStr).append(";\n");
                    sb.append("public class ").append(classStr).append("{\n");
                    ArrayList<String> listVar = new ArrayList<>();
                    ArrayList<String> listMethod = new ArrayList<>();
                    ArrayList<String> listCommon = new ArrayList<>();
                    int count = model.getRowCount();
                    /**
                     * 
                     */
                    for (int i = 0; i < count; i++) {
                        if(!model.getValueAt(i, 2).equals(""))//如果有输入变量名
                        {
                            String common ="";
                            if(!model.getValueAt(i, 3).equals(""))
                                common = "\t/**\n\t * " + model.getValueAt(i, 3).toString()+"\n\t */\n";
                            listCommon.add(common);
                            StringBuilder sb2 = new StringBuilder();
                            sb2.append("\t");
                            if(!model.getValueAt(i, 0).equals(""))
                            {
                                sb2.append(model.getValueAt(i, 0).toString()+" ");
                            }
                            sb2.append(model.getValueAt(i, 1).toString()+" ");
                            sb2.append(model.getValueAt(i, 2).toString()+";\n");
                            listVar.add(sb2.toString());
                            sb2 = new StringBuilder();
                            sb2.append("\t/**\n\t*设置"+model.getValueAt(i, 3).toString()+"\n\t*/\n");
                            sb2.append("\tpublic void set").append(firstUpper(model.getValueAt(i, 2).toString())).append("(").
                                    append(model.getValueAt(i, 1)).append(" ").append(model.getValueAt(i, 2))
                                    .append("){\n");
                            sb2.append("\t\tthis.").append(model.getValueAt(i, 2)).append(" = ").append(model.getValueAt(i, 2)).append(";\n");
                            sb2.append("\t}\n");
                            sb2.append("\t/**\n\t*获取"+model.getValueAt(i, 3).toString()+"\n\t*/\n");
                            sb2.append("\tpublic "+model.getValueAt(i, 1).toString()+" get").append(firstUpper(model.getValueAt(i, 2).toString())).append("(){\n");
                            sb2.append("\t\treturn ").append(model.getValueAt(i, 2)).append(";\n");
                            sb2.append("\t}\n");
                            listMethod.add(sb2.toString());
                        }
                    }
                    for (int i = 0; i < listVar.size(); i++) {
                        sb.append(listCommon.get(i));
                        sb.append(listVar.get(i));
                    }
                    for (int i = 0; i < listMethod.size(); i++) {
                        sb.append(listMethod.get(i));
                    }
                    sb.append("}");
                    File f = new File(MainFrame.config.get(Constant.SRCPATH));
                    f = new File(f,packageStr.replace('.', File.separatorChar));
                    if(!f.exists())
                        f.mkdirs();
                    f = new File(f,classStr+".java");
                    try {
                        PrintWriter fw = new PrintWriter(f,MainFrame.config.get(Constant.ENCODE));
                        fw.append(sb.toString());
                        fw.close();
                        JOptionPane.showMessageDialog(frame, resourceBuddle.getString("SaveSuccess"));
                    } catch (IOException e1) {
                        JOptionPane.showMessageDialog(frame, resourceBuddle.getString("SaveFail"));
                        e1.printStackTrace();
                    }
                }
            }
        });
        getContentPane().add(btnSave);
        JButton btnClose = new JButton(resourceBuddle.getString("Close"));
        btnClose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        getContentPane().add(btnClose);

        setSize(800, 600);
        Point p = frame.getLocationOnScreen();
        p.x = p.x + (frame.getWidth() - getWidth()) / 2;
        p.y = p.y + (frame.getHeight() - getHeight()) / 2;
        setLocation(p);
    }
    
    private String firstUpper(String str)
    {
        if(str==null || str.equals(""))
            return str;
        return str.substring(0,1).toUpperCase()+str.substring(1);
    }
}